package com.mitu.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIOFileChannel3 {
    public static void main(String[] args) throws IOException {
        //创建文件输入流
        FileInputStream fileInputStream = new FileInputStream("1.txt");
        //获取文件输入通道
        FileChannel fileReadChannel = fileInputStream.getChannel();

        //创建文件输出流对象
        FileOutputStream fileOutputStream = new FileOutputStream("2.txt");
        //设置文件输出通道
        FileChannel fileWriteChannel = fileOutputStream.getChannel();

        //创建一个ByteBuffer
        ByteBuffer buffer = ByteBuffer.allocate(512);
        //循环读取
        while (true) {
            //这里有一个重要的操作，不能忘记,
            //buffer每一次读写完都要重置一下标志位(清空缓冲区中的数据)
            //要为下一次的读写做准备
            buffer.clear();
            //首先将通道的数据读到缓冲区中
            int read = fileReadChannel.read(buffer);
            if (read == -1) {
                //如果返回值为-1表示读取完毕
                break;
            }
            //读写模式转换
            buffer.flip();
            //将buffer中的数据写入到FileWriteChannel中
            fileWriteChannel.write(buffer);
        }

        //关闭通道和流
        fileReadChannel.close();
        fileWriteChannel.close();
        fileInputStream.close();
        fileOutputStream.close();
    }
}
